

var curMod = cc.Class({
    extends: cc.Component,

    properties: {
    },

    statics: {
        _instance: null,
        _isAndroid: false,
        InterstitialAdId: 'adunit-87258f8e530d8f24',
        RewardedVideoAdId: 'adunit-5a78916f386b1918',
        BannerIds: ['adunit-68e1874dee0cbf6a', 'adunit-3ffa8d72e703bbb1', 'adunit-dc61a6c0d90df79e', 'adunit-0573d264aaa792d3'], //, 'adunit-905904089942c58e'],
        tuiguangAdId: ["PBgAA840fLgpwuog"],

        ShareTitle: "看过许多美景——身边依然还是你",
        ShareImgId: '5JWEBFBdTHiZ5EcslmutbA==', // 通过 MP 系统审核的图片编号
        ShareImgUrl: 'https://mmocgame.qpic.cn/wechatgame/3gfJUsiaHCx28sibf4QvxkWEwK6UicbQricJn4M7ia9OoUIPaDXXn1tib6eSZWtpu7hOGz/0',

        _wxUserInfo: {},
        _systemInfo: {},

        Instance() {
            return curMod._instance;
        },

        GetInfo() {
            return curMod._wxUserInfo;
        },
    },

    // LIFE-CYCLE CALLBACKS:

    link() {
        require('GameMgr').Instance().sendData("login", { "code": res.code, "channelId": 1 }, function (data) {
            if (data.code === 0) {
                console.log("返回数据", data);
            }
            else {
                console.log("连接失败", data);
                return;
            };
        });
    },


    onLoad() {
        console.log('wechat onload, curMod._instance=', curMod._instance);
        if (curMod._instance) {
            return;
        }
        curMod._instance = this;

        if (!window.wx) {
            return;
        }

        //if (require('GameMgr').Instance().ApiType !== 2 && require('GameMgr').Instance().ApiType !== 1) {
        if (require('GameMgr').Instance().ApiType !== 1) {
            return;
        }
        //...
        this._bannerAd = null;
        this._intersitialAd = null;
        this._rewardedVideoAd = null;
        this.setLogin();
        if (curMod._isAndroid) {
            //console.log('curMod._isAndroid...')
            //cc.game.setFrameRate(40);
        }
        //cc.game.setFrameRate(45);

        //load all ads
        // setTimeout(() => {
        //     this.createBannerAds();
        //     this.createInterstitialAd();
        //     this.createRewardedVideoAd();
        // }, 200);

        if (cc.sys.isMobile && typeof (wx) !== "undefined" && require('GameMgr').Instance().ApiType === 1) { //WX小游戏移动设备环境下
            /*
            var tuijian = window.wx.createGamePortal(
                {
                    adUnitId: tuiguangAdId[0]
                }
            );
            console.log("%%%%   " + tuijian);
*/
            var launch = wx.getLaunchOptionsSync();
            var queryData = launch.query;
            var diyData = queryData.diy;
            if (diyData != null && diyData != "") {
                console.log("微信透传参数：" + diyData);
            }
            else {
                console.log("微信平台无透传参数");
            }
        }
        this.id = 2;

        this.scheduleOnce(this.createBannerAds, 1);
        this.scheduleOnce(this.createInterstitialAd, 10);
        var callBackFun = this.createRewardedVideoAd(0);
        this.scheduleOnce(callBackFun, 3);
    },

    showClub() {
        if (window.wx && require('GameMgr').Instance().ApiType === 1) {
            this.clubButton = wx.createGameClubButton({
                icon: 'light',
                style: {
                    left: 20, // 之所以要减20，是因为clubButton的锚点在左上角
                    top: 200, // 之所以要减20，是因为clubButton的锚点在左上角 
                    width: 40,
                    height: 40
                }
            });
            this.clubButton.show();
            return;
        }
    },

    start() {
        if (!window.wx) {
            return;
        }

        if (require('GameMgr').Instance().ApiType === 1) {
            this.showClub();
            //this.CreateGameIcon();
        }
    },

    // update (dt) {},

    shareAppMessage(i) {
        if (!window.wx) {
            return;
        }
        cc.log('shareAppMessage...');
        var MyId = 111;
        //var maxGuanqia = cc.sys.localStorage.getItem('local_guanIndex');
        var maxGuanqia = require('GameMgr').Instance().getGuanQia();
        var Score = require('GameMgr').Instance().getLogin().maxScore;
        var Rank = parseInt(maxGuanqia / 1000) + "-" + maxGuanqia % 1000;//分享内容
        var ShareTitle1 = "";
        if (i === 1) {
            ShareTitle1 = "看过许多美景——身边依然还是你";
        } else if (i === 2) {
            // ShareTitle1 = "全服第" + +"名，不服你来试试！";
            ShareTitle1 = "高分全凭手速！我在" + Rank + "关获得" + Score + "分，你敢挑战吗？";
        } else if (i === 3) {
            ShareTitle1 = "高分全凭手速！我在" + Rank + "关获得" + Score + "分，你敢挑战吗？";
        }

        if (require('GameMgr').Instance().ApiType === 1) {
            //window.wx.shareAppMessage({
            window.wx.aldShareAppMessage({
                title: ShareTitle1,
                imageUrlId: curMod.ShareImgId,
                imageUrl: curMod.ShareImgUrl,
                query: "id:" + MyId,
            });
        }
        this.closeTime = new Date().getTime();
        this._shareTime = new Date().getTime();
        this.isShared = true;
    },

    showInterstitialAd() {
        if (!window.wx) {
            return;
        }
        if (!this._intersitialAd) {
            this.createInterstitialAd();
            return;
        }
        this._intersitialAd.show();
    },


    showRewardedVideoAd(index) {
        if (!window.wx) {
            return;
        }
        if (!this._rewardedVideoAd) {
            return;
        }
        //this.createRewardedVideoAd(i);
        if (require('GameMgr').Instance().ApiType === 1) {
            if (this._rewardedVideoAd) {
                this._rewardedVideoAd.show();
            }
            else {
                this.scheduleOnce(this.createRewardedVideoAd, 3);
            }
        }
    },



    showBannerAd(index) {
        if (!window.wx) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        for (let i = 0; i < this._bannerAds.length; i++) {
            if (i != index) {
                this._bannerAds[i].hide();
            }
        }
        console.log(index)
        if (this._bannerAds[index]) {
            console.log("this._bannerAds", this._bannerAds[index])
            if (require('GameMgr').Instance().ApiType === 1) {
                this._bannerAds[index].show();
            }
        }
    },

    hideBannerAd(index) {
        if (!window.wx) {
            return;
        }
        this.hideBannerAds();
        if (this._bannerAds && index < this._bannerAds.length && this._bannerAds[index]) {
            this._bannerAds[index].hide();
        }
    },

    //隐藏所有广告
    hideBannerAds() {
        if (!window.wx) {
            return;
        }
        if (!this._bannerAds) {
            return;
        }
        if (this._bannerAds && this._bannerAds.length != null) {
            if (this._bannerAds.length > 0) {
                for (var i = 0; i < this._bannerAds.length; i++) {
                    if (this._bannerAds && this._bannerAds[i]) {
                        this._bannerAds[i].hide();
                    }
                }
            }
        }
    },

    createBannerAds() {
        let winSize = curMod._systemInfo; //wx.getSystemInfoSync();
        let bannerHeight = 130;
        let bannerWidth = 300;

        this._bannerAds = [];
        var length = curMod.BannerIds.length;
        for (let i = 0; i < length; i++) {
            if (require('GameMgr').Instance().ApiType === 1) {
                let banner = wx.createBannerAd({
                    adUnitId: curMod.BannerIds[i],
                    adIntervals: 30,
                    style: {
                        left: (winSize.windowWidth - bannerWidth) / 2,
                        top: winSize.windowHeight - bannerHeight,
                        width: bannerWidth,
                    }
                });
                banner.onError(function (res) {
                    console.log('banner, ', res);
                });
                this._bannerAds[i] = banner;
            }
        }

        // this._bannerAdTop = wx.createBannerAd({
        //     adUnitId: curMod.BannerAdTopId,
        //     style: {
        //         left: (winSize.windowWidth - bannerWidth) / 2,
        //         top: 0,
        //         width: bannerWidth,
        //     }
        // })
        // this._bannerAdTop.onError(function (res) {
        //     console.log('_bannerAdTop, errMsg=' + JSON.stringify(res));
        // });

        // this._bannerAdBottom = wx.createBannerAd({
        //     adUnitId: curMod.BannerAdBottomId,
        //     adIntervals: 60,
        //     style: {
        //         left: (winSize.windowWidth - bannerWidth) / 2,
        //         top: winSize.windowHeight - bannerHeight,
        //         width: bannerWidth,
        //     }
        // })
        // this._bannerAdBottom.onError(function (res) {
        //     console.log('_bannerAdBottom, errMsg=' + JSON.stringify(res));
        // });
    },

    createInterstitialAd() {
        let self = this;

        if (this._intersitialAd) {
            return;
        }

        if (require('GameMgr').Instance().ApiType === 1) {
            this._intersitialAd = wx.createInterstitialAd({
                adUnitId: curMod.InterstitialAdId,
            })
        }
        //console.log('this._intersitialAd=' + this._intersitialAd);
        this._intersitialAd.onError(function (res) {
            console.log('_intersitialAd, errMsg=' + JSON.stringify(res));
            wx.showToast({
                title: 'load ad failed！',
                icon: 'success',
                duration: 2000
            });
            setTimeout(() => {
                self.createInterstitialAd();
            }, 5000);
        });
        this._intersitialAd.onClose(function (res) {
            console.log('_intersitialAd, onClose, res=' + JSON.stringify(res));
            require('GameMgr').onWxShow();
        });

        if (!this._intersitialAd) {
            this.scheduleOnce(function () {
                this.createInterstitialAd();
            }, 1);
            return;
        }
        this._intersitialAd.load();
        //this._intersitialAd.show();
    },

    craetTTRecorder() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        this.state = 0;
        this.RecorderManager = tt.getGameRecorderManager();
        //录屏开始
        this.RecorderManager.onStart(res => {
            console.log('录屏开始');
            var url = "lank_ico/TTvideo1";
            require('GameMgr').Instance().setPic(url);
            require('GameMgr').Instance().VideoShareShow(false);
            require('GameMgr').Instance().SetVTimer();
            this.state = 1;
        });
        this.RecorderManager.onStop(res => {
            console.log(res.videoPath);
            console.log('录屏结束');
            //var url = "lank_ico/TTvideo0";
            //if (require('GameMgr').Instance().getLogin().screenBan) {
            var url = "lank_ico/videoStart";
            //}
            require('GameMgr').Instance().setPic(url);
            require('GameMgr').Instance().stopVTimer();
            this.videoPath = res.videoPath;
            if (this.videoPath) {
                require('GameMgr').Instance().VideoShareShow(true);
            }
            this.state = 0;
        });
    },

    TTShareVideo() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (!this.videoPath) {
            return;
        }
        tt.shareAppMessage({
            channel: "video",
            title: "分享视频",
            desc: "分享精彩一刻",
            imageUrl: "",
            templateId: "", // 替换成通过审核的分享ID
            query: "",
            extra: {
                videoPath: this.videoPath, // 可替换成录屏得到的视频地址
                videoTopics: ["录屏分享", "小游戏"]
            },
            success() {
                require('GameMgr').Instance().VideoShareShow(false);
                console.log("分享视频成功");
                if (require('GameMgr').Instance().getLogin().screenBan) {
                    return;
                }
                require('GameMgr').Instance().sendData("setScreenBan", { "screenBan": 1 }, function (data) {
                    if (data.code === 0) {
                        console.log("返回数据", data);
                        /*
                        require('GameMgr').Instance().showTip("分享成功！获得<img src='enjoy1'/> x 1", 0, "取消", "确定", function () {
                        }, function () {
                        });*/
                        require('GameMgr').Instance().setEnergy(1);
                        require('GameMgr').Instance().hidVideoBtn();
                    }
                    else {
                        console.log("连接失败", data);
                        return;
                    };
                });
            },
            fail(e) {
                require('GameMgr').Instance().VideoShareShow(false);
                console.log("分享视频失败", e);
                if (e.errMsg !== "shareAppMessage:cancel") {
                    require('GameMgr').Instance().showTip("分享视频失败,录制时间过短", 0, "取消", "确定", function () {
                    }, function () {
                    });
                }
            }
        });
    },

    TTRecorderCheck() {
        if (require('GameMgr').Instance().ApiType !== 2) {
            return;
        }
        if (this.state === 0) {
            this.RecorderManager.start({
                duration: 30,
            })
        }
        else if (this.state === 1) {
            this.RecorderManager.stop();
        }
    },

    createRewardedVideoAd(number) {
        if (this._rewardedVideoAd) {
            return;
        }
        if (!window.wx) {
            return;
        }
        if (require('GameMgr').Instance().ApiType === 1) {
            this._rewardedVideoAd = wx.createRewardedVideoAd({
                adUnitId: curMod.RewardedVideoAdId
            });
        }

        this._rewardedVideoAd.onError(function (res) {
            //console.log('onError, _rewardedVideoAd, res=' + JSON.stringify(res));
            wx.showToast({
                title: 'load ad failed！',
                icon: 'success',
                duration: 2000
            });
        });

        this.WatchVAD = false;
        this._rewardedVideoAd.onClose(function (res) {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined

            console.log(res)
            console.log(this.id)
            if (res && res.isEnded || res === undefined) {
                this.WatchVAD = true;
                if (require('GameMgr').Instance().ApiType === 1) {
                    require('GameMgr').Instance().ShowADrewords();
                    // 正常播放结束，可以下发游戏奖励
                    require('GameMgr').Instance().setDaily(2);
                }

            }
            else {
                // 播放中途退出，不下发游戏奖励
                require('GameMgr').Instance().onAddExit();
            }
        });
        this._rewardedVideoAd.onError((err) => {
            require('GameMgr').Instance().showTip(err + "\n请稍后再试", 0, "取消", "确定", function () {
            }, function () {
            });
        });
        this._rewardedVideoAd.load();
        //this._rewardedVideoAd.show();
    },

    wxGameStart(id) {
        if (!window.wx || require('GameMgr').Instance().ApiType !== 1) {
            return;
        }
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        cc.log(Id);
        if (!window.wx) {
            return;
        }
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        cc.log(Id);
        var stagename = "第" + parseInt(id / 1000) + "-" + (id % 1000) + "关";
        wx.aldStage.onStart({
            stageId: Id,     //关卡ID 该字段必传
            stageName: stagename, //关卡名称  该字段必传
            //userId: "06_bmjrPtlm6_2sgVt7hMZOPfL2M" //用户ID 可选
        })
    },

    wxGameING(id, number) {
        if (!window.wx || require('GameMgr').Instance().ApiType !== 1) {
            return;
        }
        // 在关卡中使用道具
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        var stagename = "第" + parseInt(id / 1000) + "." + (id % 1000) + "关";
        var msg = "";
        if (number === 1) {
            msg = "吸金币";
        }
        else if (number === 2) {
            msg = "二段跳";
        }
        wx.aldStage.onRunning({
            stageId: Id,
            stageName: stagename,
            //userId: "123456",
            event: "tools",
            params: {
                itemName: msg,
            }
        });
    },

    wxGameOver(id, state) {
        //关卡完成
        if (!window.wx || require('GameMgr').Instance().ApiType !== 1) {
            return;
        }
        var Id = parseInt(id / 1000) + "." + (id % 1000);
        var stagename = "第" + parseInt(id / 1000) + "." + (id % 1000) + "关";
        var complete = "";
        if (state === 0) {
            complete = "死亡";
            state = "fail";
        }
        else if (state === 1) {
            complete = "复活";
            state = "fail";
        } else if (state === 2) {
            complete = "通关";
            state = "complete";
        } else if (state === 3) {
            complete = "重新开始";
            state = "fail";
        }
        wx.aldStage.onEnd({
            stageId: Id,    //关卡ID 该字段必传
            stageName: stagename, //关卡名称  该字段必传
            //userId: "06_bmjrPtlm6_2sgVt7hMZOPfL2M",  //用户ID 可选
            event: state,   //关卡完成  关卡进行中，用户触发的操作    该字段必传
            params: {
                desc: complete,  //描述
            }
        })
    },

    PYQshow() {
        if (window.wx && require('GameMgr').Instance().ApiType === 1) {
            this.clubButton.show();
            return;
        }
    },
    PYQhid() {
        if (window.wx && require('GameMgr').Instance().ApiType === 1) {
            this.CreateGameIcon();
            this.clubButton.hide();
            if (this.shareAd) {
                this.shareAd.hide();
            }
            return;
        }
    },

    CreateGameIcon() {
        if (!window.wx || require('GameMgr').Instance().ApiType !== 1) {
            return;
        }
        return;
        console.log("CreateGameIcon=======");
        // 在适合的场景显示推荐位 
        if (this.s_GameIconInterstitialLoaded) {
            return;
        }
        this.s_GameIconInterstitialLoaded = false;
        var self = this;
        this.shareAd = wx.createGameBanner(
            {
                adUnitId: curMod.tuiguangAdId[0],
            },
            {
            }
        );
        this.shareAd.onLoad(() => {
        })
        this.shareAd.onResize(size => {
            console.log('CreateGameIcon 广告加载成功');
            this.s_GameIconInterstitialLoaded = true;
            this.shareAd.show();
            console.log(this.shareAd);
        }
        );
        console.log('CreateGameIcon 广告加载成功');
        console.log(this.shareAd);
        this.shareAd.onError(err => {
            this.s_GameIconInterstitialLoaded = false;
            console.log(err);
            console.error("CreateGameIcon 加载失败" + err.errMsg + " code=" + err.errCode);
        })
        return;

    },



    setLogin() {
        // let isWeChat = (cc.sys.platform === cc.sys.WECHAT_GAME);
        if (require('GameMgr').Instance().ApiType !== 1) {
            return;
        }
        let self = this;

        let sysInfo = window.wx.getSystemInfoSync();
        curMod._systemInfo = sysInfo;

        wx.login({
            success(res) {
                console.log('请求登录');
                console.log(res)
                if (res.code) {
                    console.log('微信登录成功！')
                    console.log(res)
                    //发起网络请求
                    require('GameMgr').Instance().setresCode(res.code);
                    var id = require('GameMgr').Instance().ApiType;
                    console.log("渠道ID：" + id);

                    let self1 = self;
                    require('GameMgr').Instance().sendData("login", { "code": res.code, "channelId": id }, function (data) {
                        if (data.code === 0) {
                            console.log("返回数据", data);
                            require('GameMgr').Instance().setLogin(data.uid, data.token, data);
                            //require('GameMgr').Instance().setGameStart();
                            self1.getWeiXinInfo();
                        }
                        else {
                            console.log("连接失败", data);
                            cc.director.loadScene('LoadScene');
                            return;
                        }
                    });

                    // cc.log(url);
                } else {
                    self.scheduleOnce(function () {
                        self.setLogin();
                    }, 0.5);
                    console.log('登录失败！' + res.errMsg)
                }
            },
            complete() {
                console.log('登录调用完成');
            },
            fail() {
                console.log('再次登录');
                self.scheduleOnce(function () {
                    self.setLogin();
                }, 0.5);
            },
        })
    },

    /**
     * 获取微信信息
     */
    getWeiXinInfo() {
        let isWeChat = (cc.sys.platform === cc.sys.WECHAT_GAME);
        if (!isWeChat || !window.wx) {
            return;
        }
        let self = this;

        wx.showShareMenu({
        });
        /*
                wx.login({
                    success(res) {
                        if (res.code) {
                            console.log('登录成功！')
                            console.log(res)
                            //发起网络请求
                            require('GameMgr').Instance().setresCode(res.code);
                            var id = require('GameMgr').Instance().ApiType;
                            console.log("渠道ID：" + id);
        
                            require('GameMgr').Instance().sendData("login", { "code": res.code, "channelId": id }, function (data) {
                                if (data.code === 0) {
                                    console.log("返回数据", data);
                                    require('GameMgr').Instance().setLogin(data.uid, data.token, data);
                                    //require('GameMgr').Instance().setGameStart();
                                }
                                else {
                                    console.log("连接失败", data);
                                    cc.director.loadScene('LoadScene');
                                    return;
                                }
                            });
        
                            // cc.log(url);
                        } else {
                            console.log('登录失败！' + res.errMsg)
                        }
                    }
                })
        */
        //wx.onShareAppMessage(function () {
        if (require('GameMgr').Instance().ApiType === 1) {
            wx.aldOnShareAppMessage(function () {
                return {
                    title: curMod.ShareTitle,
                    imageUrlId: curMod.ShareImgId,
                    imageUrl: curMod.ShareImgUrl,
                }
            });
        }

        wx.onShow(function (para) {
            //console.log('onShow...' + JSON.stringify(para));
            if (require('GameMgr').Instance().ApiType === 1) {
                if (self.isShared) {
                    require('GameMgr').Instance().setDaily(5);
                    //分享后返回
                    let curTime = new Date().getTime();
                    console.log(curTime - self.closeTime);
                    if (curTime - self.closeTime >= 300) {
                        //分享成功
                        console.log("分享成功");
                        self.closeTime = curTime;
                    }
                }
                require('GameMgr').onWxShow(new Date().getTime() - self._shareTime);
            }
        });

        wx.onHide(function (para) {
            //console.log('onHide...' + JSON.stringify(para));
        });
        let sysInfo = window.wx.getSystemInfoSync();
        //获取微信界面大小
        let width = sysInfo.screenWidth;
        let height = sysInfo.screenHeight;

        curMod._systemInfo = sysInfo;
        this.printInfo(sysInfo);

        window.wx.getSetting({
            success(res) {
                //console.log(res.authSetting);
                if (res.authSetting["scope.userInfo"]) {
                    //console.log("用户已授权");
                    window.wx.getUserInfo({
                        success(res) {
                            //console.log(res);
                            curMod._wxUserInfo = res.userInfo;
                            //此时可进行登录操作
                            console.log('curMod._wxUserInfo=' + JSON.stringify(curMod._wxUserInfo));
                            var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                            console.log(curMod._wxUserInfo);
                            var name = curMod._wxUserInfo.nickName;
                            require('GameMgr').Instance().setplUrl(imgurl);
                        }
                    });
                } else {
                    if (require('GameMgr').Instance().ApiType === 1) {
                        //console.log("用户未授权");
                        let button = window.wx.createUserInfoButton({
                            type: 'text',
                            text: '',
                            style: {
                                left: 0,
                                top: 0,
                                width: width,
                                height: height,
                                backgroundColor: '#00000000',//最后两位为透明度
                                color: '#ffffff',
                                fontSize: 20,
                                textAlign: "center",
                                lineHeight: height,
                            }
                        });
                        button.onTap((res) => {
                            if (res.userInfo) {
                                //console.log("用户授权:", res);
                                curMod._wxUserInfo = res.userInfo;
                                //此时可进行登录操作
                                console.log('curMod._wxUserInfo=' + JSON.stringify(curMod._wxUserInfo));
                                var imgurl = curMod._wxUserInfo.avatarUrl + "?aaa=aa.jpg";
                                console.log(curMod._wxUserInfo);
                                var name = curMod._wxUserInfo.nickName;

                                require('GameMgr').Instance().setplUrl(imgurl);
                                button.destroy();
                            } else {
                                //console.log("用户拒绝授权:", res);
                            }
                        });
                    }
                }
            }
        });
    },

    printInfo(res) {
        // console.log('设备品牌:', res.brand)
        // console.log('设备型号:', res.model)
        // console.log('设备像素比:', res.pixelRatio)
        // console.log('屏幕宽度:', res.windowWidth)
        // console.log('屏幕高度:', res.windowHeight)
        // console.log('状态栏的高度:', res.statusBarHeight)
        // console.log('微信设置的语言:', res.language)
        // console.log('微信版本号:', res.version)
        // console.log('操作系统及版本:', res.system)
        // console.log('客户端平台:', res.platform)
        // console.log('用户字体大小:', res.fontSizeSetting)
        // console.log('客户端基础库版本 :', res.SDKVersion)
        // console.log('设备性能等级:', res.benchmarkLevel)

        if (res.system.indexOf('Android') != -1) {
            curMod._isAndroid = true;
        }
    },
});
